/**
 * 
 */
package net.jeanhwea.gold.model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import net.jeanhwea.gold.bean.Item;

import java.sql.Connection;

/**
 * @author Jeanhwea
 *
 */
public class ItemPeer {
	
	public static ArrayList <Item> searchItemById(DataManager dataManager, int id){
		ArrayList <Item> items = new ArrayList<Item>();
		Connection con = dataManager.getConnection();
		
		if(con != null) {
			try {
				Statement s = con.createStatement();
				String query = "SELECT * FROM inf WHERE id = " + id;
				try{
					ResultSet rs = s.executeQuery(query);
					try{
						while (rs.next()){
							Item item = new Item();
							item.setID(Integer.parseInt(rs.getString(1).trim()));
							item.setPrice(Double.parseDouble(rs.getString(2).trim()));
							item.setTime(rs.getString(3).trim());
							item.setDate(rs.getString(4).trim());
							items.add(item);
						}
					} finally{
						rs.close();
					}
				}finally{ 
					s.close(); 
				}
			} catch (SQLException e) {
				e.printStackTrace();
				System.out.println("Could not search for id: " + e.getMessage());
			} finally{
				dataManager.closeConnection(con);
			}
		}
		
		return items;
	}
	
	public static ArrayList <Item> searchItemByPrice(DataManager dataManager, double price){
		ArrayList <Item> items = new ArrayList<Item>();
		Connection con = dataManager.getConnection();
		
		if(con != null) {
			try {
				Statement s = con.createStatement();
				String query = "SELECT * FROM inf WHERE price = " + price;
				try{
					ResultSet rs = s.executeQuery(query);
					try{
						while (rs.next()){
							Item item = new Item();
							item.setID(Integer.parseInt(rs.getString(1).trim()));
							item.setPrice(Double.parseDouble(rs.getString(2).trim()));
							item.setTime(rs.getString(3).trim());
							item.setDate(rs.getString(4).trim());
							items.add(item);
						}
					} finally{
						rs.close();
					}
				}finally{ 
					s.close(); 
				}
			} catch (SQLException e) {
				e.printStackTrace();
				System.out.println("Could not search for price: " + e.getMessage());
			} finally{
				dataManager.closeConnection(con);
			}
		}
		
		return items;
	}
}
